package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.lang.model.element.VariableElement;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")//接收电话号码
    public R sendMessage(@RequestBody User user, HttpSession session) {
        //生成验证码
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        log.info("验证码为：{}", code);
        //发送验证码
        // SMSUtils.sendMessage("黑马程序员", "SMS_171354585", user.getPhone(), String.valueOf(code));
        //将验证码存储到session中
        //session.setAttribute(user.getPhone(), code);

        //将验证码缓存到redis中
        redisTemplate.opsForValue().set(user.getPhone(),code,5, TimeUnit.MINUTES);

        //响应前端
        return R.success("发送成功");
    }

    @PostMapping("/login")
    public R login(@RequestBody Map<String, String> map, HttpSession session) {
        //接收请求参数
        String code = map.get("code");
        String phone = map.get("phone");
        //获取session中存储的验证码
        //String sessionCode =  String.valueOf(session.getAttribute(phone));

        //获取redis中缓存的验证码
        String sessionCode = redisTemplate.opsForValue().get(phone).toString();

        //对比用户输入的验证码和session中的验证码是否一致
        //判断---用户输入了验证码 并且和session中存储的验证码一致
        if (sessionCode != null && sessionCode.equals(code)) {
            //登录成功---移除session中存储的验证码
            session.removeAttribute(phone);
            //根据输入的phone查询用户是否是第一次登录
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone, phone);
            User user = userService.getOne(wrapper);
            //判断user是否为空
            if (user == null) {
                //第一次登录--存储到user表中
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            //将session中的对象存储到localThread中
            Long userId = user.getId();
            session.setAttribute("user", userId);

            //登录成功后清除缓存的验证码
            redisTemplate.delete(phone);

            return R.success("登录成功");

        }
        return R.error("登录失败");
    }


}
